package com.sopaths.service;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.sopaths.contract.dao.RecruitmentDao;
import com.sopaths.contract.domain.Recruitment;
import com.sopaths.contract.service.RecruitmentService;

@Named
public class RecruitmentServiceImpl implements RecruitmentService {

	@Inject
	private RecruitmentDao recruitmentDao;

	private final Logger logger = Logger.getLogger(RecruitmentServiceImpl.class);

	@Override
	@Transactional
	public Recruitment create(Recruitment recruitment) {
		return recruitmentDao.create(recruitment);
	}

	@Override
	@Transactional
	public List<Recruitment> batchCreate(List<Recruitment> recruitments) {
		for (Recruitment recruitment : recruitments) {
			recruitmentDao.create(recruitment);
		}
		return recruitments;
	}

	@Override
	@Transactional
	public Recruitment delete(int id) {
		Recruitment recruitment = recruitmentDao.delete(id);
		return recruitment;
	}

	@Override
	@Transactional
	public Recruitment update(Recruitment recruitment) {
		recruitmentDao.update(recruitment);
		return recruitment;
	}

	@Override
	public Recruitment updateByUrl(Recruitment recruitment) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Recruitment> batchUpdateByUrl(List<Recruitment> recruitments) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@Transactional
	public Recruitment saveCrawledRecruitment(Recruitment recruitment) {
		int savedId = recruitmentDao.getIdByUrl(recruitment.getUrl());
		if (savedId == -1) {	//没有找到URL对应的recruitment记录，新建
			logger.info("Create recruitment for: " + recruitment.getUrl());
			return recruitmentDao.create(recruitment);
		} else {	//数据库中已经保存过这条recruitment信息，更新
			logger.info("Update recruitment. URL: " + recruitment.getUrl() + ". ID: " + savedId);
			recruitment.setId(savedId);
			return recruitmentDao.update(recruitment);
		}
	}

	@Override
	public Recruitment get(int id) {
		return recruitmentDao.get(id);
	}

	@Override
	public Recruitment getByUrl(String url) {
		// TODO Auto-generated method stub
		return null;
	}

	public void setRecruitmentDao(RecruitmentDao recruitmentDao) {
		this.recruitmentDao = recruitmentDao;
	}
}
